package com.dayi.activity.chatroom.childfragment;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.AnswerDetail;
import com.dayi.bean.UploadVoice;
import com.dayi.view.CommonSoundItemView;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.fastkit.views.recyclerview.tool.MyLinearLayoutManager;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

@Route(path = ARouterPathUtils.Dayi_FragmentStudentTeacherFirst)
public class TeacherFirstFragment extends BaseAppFragment {

    private static int MESSAGE_TEXT = 0;
    private static int MESSAGE_IMAGE = 1;
    private static int MESSAGE_VOICE = 2;

    @BindView(R2.id.sv_contain)
    ScrollView svContain;
    @BindView(R2.id.iv_question)
    ImageView ivQuestion;
    @BindView(R2.id.rv_message)
    RecyclerView rvMessage;

    ChatMessageAdapter messageAdapter;


    private List<AnswerDetail> messageList = new ArrayList<>();

    //用于装载已经成功上传的语音
    private Map<String, UploadVoice> voiceMap = new HashMap<>();

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        initStudentChat();

    }

    public void updateChatMsg(AnswerDetail answerDetail) {
        if (answerDetail != null) {
            messageList.add(answerDetail);
        }
        messageAdapter.notifyDataSetChanged();

        LogUtil.e("TeacherFirstFragment中messageAdapter的长度为：" + messageAdapter.getItemCount());

        if (messageAdapter.getItemCount() > 0) {
            rvMessage.smoothScrollToPosition(messageAdapter.getItemCount() - 1);
        }

        svContain.post(new Runnable() {
            @Override
            public void run() {
                svContain.fullScroll(View.FOCUS_DOWN);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_room_student;
    }

    private void initStudentChat() {

        AnswerDetail answerDetail1 = new AnswerDetail();
        AnswerDetail answerDetail2 = new AnswerDetail();

        AnswerDetail.ObjBean objBean1 = new AnswerDetail.ObjBean();
        objBean1.setIs_check(1);
        objBean1.setCorrect("学生发送的");
        answerDetail1.setObj(objBean1);

        AnswerDetail.ObjBean objBean2 = new AnswerDetail.ObjBean();
        objBean2.setIs_check(2);
        objBean2.setCorrect("老师发送的");
        answerDetail2.setObj(objBean2);

        messageList.add(answerDetail1);
        messageList.add(answerDetail2);

        messageAdapter = new ChatMessageAdapter(getActivity(), messageList);
        MyLinearLayoutManager manager = new MyLinearLayoutManager(getActivity());
        rvMessage.setLayoutManager(manager);
        rvMessage.setAdapter(messageAdapter);

        if (messageAdapter.getItemCount() > 0) {
            rvMessage.smoothScrollToPosition(messageAdapter.getItemCount() - 1);
        }

        svContain.post(new Runnable() {
            @Override
            public void run() {
                svContain.fullScroll(View.FOCUS_DOWN);
            }
        });

    }

    class ChatMessageAdapter extends BaseAdapter<AnswerDetail> {

        public ChatMessageAdapter(Context context, List<AnswerDetail> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_chat_message;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<AnswerDetail> mData) {

            LinearLayout linReceive = holder.getView(R.id.lin_receive);

            LinearLayout linSend = holder.getView(R.id.lin_send);

            //假设1代表发送
            if (mData.get(position).getObj().getIs_check() == 1) {
                //隐藏左侧接收item
                linReceive.setVisibility(View.GONE);
                //发送人头像
                ImageView ivSend = holder.getView(R.id.iv_send);
                //发送消息，根据类型向该容器中添加相应控件，文字--图片--语音
                LinearLayout linSendMsg = holder.getView(R.id.lin_send_msg);

                TextView tvSend = holder.getView(R.id.tv_send);
                tvSend.setText(mData.get(position).getObj().getCorrect());

                if ("linSendMsg.type".equals("image")) {
                    ImageView ivContent = new ImageView(getActivity());
                    ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(200, 200);
                    ivContent.setLayoutParams(params);
                    Glide.with(getActivity())
                            .load("")
                            .apply(GlideConfig.getRoundOptions(10))
                            .into(ivContent);
                    linSendMsg.addView(ivContent);

                } else if ("linSendMsg.type".equals("text")) {

                    TextView tvSend1 = holder.getView(R.id.tv_send);
                    tvSend.setText(mData.get(position).getObj().getCorrect());
                    tvSend.setSingleLine(false);
                    tvSend.setTextSize(14);
                    tvSend.setMaxWidth(250);
                    linSendMsg.addView(tvSend);
                } else if ("linSendMsg.type".equals("voice")) {

                    instertVoice(linSendMsg, "", true);
                }


            } else {
                //隐藏右侧发送item
                linSend.setVisibility(View.GONE);
                //接收人头像
                ImageView ivReceive = holder.getView(R.id.iv_receive);
                //收到消息，根据类型向该容器中添加相应控件，文字--图片--语音
                LinearLayout linReveiveMsg = holder.getView(R.id.lin_receive_msg);

                TextView tvReceive = holder.getView(R.id.tv_receive);
                tvReceive.setText(mData.get(position).getObj().getCorrect());

                if ("linReveiveMsg.type".equals("image")) {
                    ImageView ivContent = new ImageView(getActivity());
                    ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(200, 200);
                    ivContent.setLayoutParams(params);
                    Glide.with(getActivity())
                            .load("")
                            .apply(GlideConfig.getRoundOptions(10))
                            .into(ivContent);
                    linReveiveMsg.addView(ivContent);

                } else if ("linReveiveMsg.type".equals("text")) {

                    TextView tvReceive1 = holder.getView(R.id.tv_receive);
                    tvReceive.setText(mData.get(position).getObj().getCorrect());
                    tvReceive.setSingleLine(false);
                    tvReceive.setTextSize(14);
                    tvReceive.setMaxWidth(250);
                    linReveiveMsg.addView(tvReceive);
                } else if ("linReveiveMsg.type".equals("voice")) {

                    instertVoice(linReveiveMsg, "", true);
                }

            }

        }
    }


    private void instertVoice(LinearLayout linVoice, String url, boolean isDletedAble) {


        UploadVoice uploadVoice = new UploadVoice();
        uploadVoice.setPlayUrl(url);

        final CommonSoundItemView commonSoundItemView = new CommonSoundItemView(getContext());
        commonSoundItemView.isLocalVoice(false);

        commonSoundItemView.isDletedAble(isDletedAble);

        commonSoundItemView.setAudioEntity(uploadVoice);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        params.topMargin = DisplayUtil.dip2px(getContext(), 16);
        commonSoundItemView.setLayoutParams(params);

        linVoice.addView(commonSoundItemView);

    }


}
